import { defineComponent, computed, h, resolveComponent } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { type RouteRecordRaw, RouterLink } from 'vue-router'
import { type MenuOption, NLayoutSider, NMenu, NIcon } from 'naive-ui'
import { storeToRefs } from 'pinia'
import path from 'path'

import { useAppStore } from '@/store/app'

import { isExternal } from 'utils/validate'

function resolvePath(basePath: string, routePath: string) {
  if (isExternal(routePath)) return routePath

  if (isExternal(basePath)) return basePath

  return path.resolve(basePath, routePath)
}

function buildMenu(route: RouteRecordRaw[], basePath = '/') {
  const queue = [...route]
  const result: MenuOption[] = []

  while (queue.length) {
    const current = queue.shift()!

    if (current.meta?.hidden) continue

    const target: MenuOption = Object.create(null)

    target.key = resolvePath(basePath, current.path)

    target.label = function () {
      if (current.children && current.children.length) {
        return current.meta?.title
      }

      return <RouterLink to={resolvePath(basePath, current.path)}>{current.meta?.title}</RouterLink>
    }

    target.icon = function () {
      return current.meta && current.meta.icon && <NIcon>{h(resolveComponent(current.meta.icon))}</NIcon>
    }

    if (current.children && current.children.length) {
      target.children = buildMenu(current.children, current.path)
    }

    result.push(target)
  }

  return result
}

export default defineComponent({
  name: 'AppSidebar',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const options: MenuOption[] = buildMenu(router.options.routes)

    const appStore = useAppStore()
    const { sidebar } = storeToRefs(appStore)

    const activeMenu = computed(() => {
      if (route.meta.activeMenu) {
        return route.meta.activeMenu
      }

      return route.path
    })

    return { sidebar, options, activeMenu }
  },
  render() {
    return (
      <NLayoutSider
        bordered
        position='static'
        collapse-mode='width'
        collapsed-width={64}
        width={200}
        native-scrollbar={false}
        collapsed={this.sidebar.opened}
        class='app-sidebar'>
        <NMenu
          value={this.activeMenu}
          collapsed-width={64}
          ollapsed-icon-size={22}
          options={this.options}
          builtinThemeOverrides={{
            itemIconColor: '#bfcbd9',
            itemIconColorHover: '#bfcbd9',
            itemTextColor: '#bfcbd9',
            itemColorHover: '#263445',
            itemTextColorHover: '#bfcbd9',
            itemIconColorCollapsed: '#bfcbd9'
          }}
        />
      </NLayoutSider>
    )
  }
})
